# -*- coding:utf-8 -*-
#!/usr/bin/python
import re
from common import *
from splinter import Browser
from sql_cases import *
from urlparse import urlparse,urlunparse
from urllib import urlencode

class SQL_Injection(Basis):
    
#     def __init__(self,browser,url):
#         self.browser=browser
#         self.url=url
#         
    def seturl(self,url):
        self.url=url
        
    def prepare(self):
        self.browser.visit(self.url)
        try:
            self.input_vector=self.browser.find_by_xpath("//input[@type='text']").first
            self.submit=self.browser.find_by_xpath("//input[@type='submit']").first
            return True
        except:
            pass
        return False
    
    def DetectContent(self):
        if self.prepare():
            for case in sql_cheat_sheet:
                if self.prepare():
                    self.input_vector.fill(case)
                    self.submit.click()
                    if self.browser.status_code == 500:
                        return self.browser.url
                    for (type,mats) in sql_error_sheet.items():
                        for mat in mats:
                            try:
                                if re.search(r"%s" % mat,self.browser.html,re.I):
                                        return self.browser.url
                            except:
                                pass
                            
        return False
    
    def DetectUrlParams(self):
        origin,totest=super(SQL_Injection,self).parseQuery("sql")
        u=urlparse(self.url)
        sql_url=[]
        for get_key in totest.keys():
              temp=origin[get_key]
              signal=0
              for case in sql_cheat_sheet:
                     origin[get_key]=case
                     query=urlencode(origin)
                     origin[get_key]=temp
                     url_test=urlunparse((u.scheme,u.netloc,u.path,u.params,query,u.fragment))
                     self.browser.visit(url_test)
                     for (type,mats) in sql_error_sheet.items():
                            for mat in mats:
                                try:
                                    if re.search(r"%s" % mat,self.browser.html,re.I):
                                        sql_url.append(self.browser.url)
                                        signal=1
                                        break
                                except:
                                        pass
                            if signal==1:
                                break
                     if signal==1:
                         break
        return sql_url
    
    def start(self):
        res = self.DetectContent()
        if res:
            print self.url+": content exists sql injection vulnerability"
        res2=self.DetectUrlParams()
        if len(res2)>0:
            for sql_url in res2:
                print sql_url+": exists sql injection vulnerability"
         
